package com.ht.api.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ht.api.bean.AjaxResult;

/**
 * 文件上传
 * @author asq
 * @createTime 2024年12月31日 22:14:50
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${upload.path}")
    private String uploadPath;
    
    @Value("${upload.domain}")
    private String domain;

    /**
     * 上传单个图片
     */
    @PostMapping("/image")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("请选择图片文件");
        }
        
        try {
            String url = saveFile(file);
            return AjaxResult.success().put("url", url);
        } catch (IOException e) {
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传多个图片
     */
    @PostMapping("/images")
    public AjaxResult uploadImages(@RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return AjaxResult.error("请选择图片文件");
        }

        List<String> urls = new ArrayList<>();
        
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    String url = saveFile(file);
                    urls.add(url);
                } catch (IOException e) {
                    return AjaxResult.error("文件上传失败：" + e.getMessage());
                }
            }
        }
        
        return AjaxResult.success().put("urls", urls);
    }

    /**
     * 保存文件的公共方法
     */
    private String saveFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        String filePath = uploadPath + fileName;
        file.transferTo(new File(filePath));
        
        return domain + "/file/upload/images/" + fileName;
    }
}